/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.DAO;

import com.Entity.Employee;
import com.Interface.EmployeeInterface;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

/**
 *
 * @author Vi
 */
@Stateless
public class EmployeeDAO implements EmployeeInterface{

    private EntityManager entityManager;
    
    public EmployeeDAO() {
        EntityManagerFactory factory = Persistence.createEntityManagerFactory("persistenceUnit");
        entityManager = factory.createEntityManager();
    }
      
    @Override
    public List<Employee> getAllEmployees() {
        return (List<Employee>) entityManager.createNamedQuery("Employee.findAll").getResultList();
    }

    @Override
    public Employee getEmployee(int idEmployee) {
        return (Employee)entityManager.createQuery( "select e from Employee e where e.idEmployee = " + idEmployee ).getSingleResult();
    }

    @Override
    public Employee addEmployee(Employee emp) {
        entityManager.getTransaction().begin();
        entityManager.persist(emp);
        entityManager.getTransaction().commit();
        return emp;
    }

    @Override
    public void removeEmployeeById(Integer id) {
        Employee rowToDelete = getEmployee(id);
        entityManager.getTransaction().begin();
        entityManager.remove(rowToDelete);
        entityManager.getTransaction().commit();
    }

    @Override
    public void updateEmployee(Employee emp) {
      
            Employee actual = getEmployee(emp.getIdEmployee());
            entityManager.getTransaction().begin();
            entityManager.persist(actual);
            actual.setName(emp.getName());
            actual.setSurname(emp.getSurname());
            actual.setPosition(emp.getPosition());
            actual.setEducation(emp.getEducation());
            actual.setCertifications(emp.getCertifications());
            actual.setEmployment(emp.getEmployment());
            actual.setDateEmployment(emp.getDateEmployment());
            actual.setWorkIt(emp.getWorkIt());
            actual.setOtherProjects(emp.getOtherProjects());
            actual.setTimeOtherProjects(emp.getTimeOtherProjects());
            entityManager.getTransaction().commit();
        
    }
    
    
}
